// 版权归 瞄你个汪 所有。使用本代码应遵守相关法律法规和Apache 2.0开源许可要求。
package top.geeke.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.geeke.entity.SysApp;
import top.geeke.entity.SysTenant;
import top.geeke.entity.SysUser;
import top.geeke.eunm.SysErrorEnum;
import top.geeke.eunm.SysStatusEnum;
import top.geeke.mapper.SysAppMapper;
import top.geeke.mapper.SysTenantMapper;
import top.geeke.mapper.SysUserMapper;
import top.geeke.service.ISysUserService;
import top.geeke.toolkit.http.AppException;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 * @author 瞄你个汪
 * @since 2024-01-01 12:00:00
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Resource
    private SysTenantMapper sysTenantMapper;
    @Resource
    private SysAppMapper sysAppMapper;

    @Override
    public SysUser getByAccountAndHost(String account, String host) {
        return getUserByAccountAndTenant(account, sysTenantMapper.getByHost(host));
    }

    @Override
    public SysUser getByAccountAndDomainCode(String account, String code) {
        return getUserByAccountAndTenant(account, sysTenantMapper.getByCode(code));
    }

    private SysUser getUserByAccountAndTenant(String account, SysTenant tenant) {
        if (tenant == null) throw new AppException(SysErrorEnum.R4007);

        if (SysStatusEnum.Enabled != tenant.getStatus()) {
            throw new AppException(SysErrorEnum.R4009);
        }

        // 租户过期3天禁止登录
        LocalDateTime expiredDate = tenant.getExpiredDate();
        if (expiredDate == null || !expiredDate.isAfter(LocalDateTime.now().plusDays(3))) {
            throw new AppException(SysErrorEnum.R4008);
        }

        SysApp app = sysAppMapper.selectById(tenant.getAppId());
        if (app == null) throw new AppException(SysErrorEnum.R4010);
        tenant.setApp(app);

        SysUser user = baseMapper.getUserByAccountAndTenant(account, tenant.getId());
        user.setTenant(tenant);

        return user;
    }
}
